import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.CountDownLatch;

/**
 * Author :  Rocky
 * Date : 24/05/2017 23:08
 * Description :
 * Test :
 */
public class MultiThreadMultiFilesTest {

    public static void main(String[] args) throws InterruptedException {
        long s = System.currentTimeMillis();

        for (int j = 0; j < 10; j++) {
            CountDownLatch latch = new CountDownLatch(10);
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            byte data = 4;
                            File file = new File("testfile" + finalI);
                            if (file.exists()) {
                                file.delete();
                            }
                            RandomAccessFile raf = new RandomAccessFile(file, "rw");
                            MappedByteBuffer mbb = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 200 * 1024 * 1024);

                            while (mbb.hasRemaining()) {
                                mbb.put(data);
                            }

                            
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        latch.countDown();
                    }
                });
                t.start();
            }
            latch.await();
        }

        long time = (System.currentTimeMillis() - s);
        long totalBytes = 20000; //单位m
        System.out.println("10个线程10个文件，每个线程负责写一个文件，各写200m，循环10次， 总耗时 " + time + " ms ，速度 " + (totalBytes * 1024 / (time * 1.0 / 1000)) + " kb/s");

    }
}
